package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.controller.utils.A;
import com.example.controller.utils.R;
import com.example.domain.Book;
import com.example.service.IBookService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private IBookService bookService;

    @GetMapping
    public A getAll() {
        return new A(true, bookService.list(), "操作成功^_^");
    }

    @PostMapping
    public A save(@RequestBody Book book) {
        if (book.getName() == null || Strings.isEmpty(book.getName())) {
            return new A(false, "书籍名称不能为空");
        } else if (book.getType() == null || Strings.isEmpty(book.getType())) {
            return new A(false, "书籍类型不能为空");
        } else {
            boolean flag = bookService.save(book);
            return new A(flag, flag ? "添加成功^_^" : "添加失败-_-!");
        }
    }

    @PutMapping
    public A update(@RequestBody Book book) {
        if (book.getName() == null || Strings.isEmpty(book.getName())) {
            return new A(false, "书籍名称不能为空");
        } else if (book.getType() == null || Strings.isEmpty(book.getType())) {
            return new A(false, "书籍类型不能为空");
        } else {
            boolean flag = bookService.updateById(book);
            return new A(flag, flag ? "修改成功^_^" : "修改失败-_-!");
        }
    }

    @DeleteMapping("{id}")
    public A delete(@PathVariable Integer id) {
        boolean flag = bookService.removeById(id);
        return new A(flag, flag ? "删除成功^_^" : "删除失败-_-!");
    }

    @GetMapping("{id}")
    public A getById(@PathVariable Integer id) {
        return new A(true, bookService.getById(id), "操作成功^_^");
    }

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize, Book book) {
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        lqw.like(Strings.isNotEmpty(book.getName()), Book::getName, book.getName());
        IPage<Book> page = new Page<>(currentPage, pageSize);
        bookService.page(page, lqw);
        return new R(true, page.getRecords(), "操作成功^_^", page.getTotal());
    }
}
